package com.a4studio.android.newsreader;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
//android tts
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.a4studio.android.util.NewsItem;
import com.a4studio.android.util.NewsPersistence;

//import com.google.tts.TTS;

//for android native tts
public class RadioActivity extends ListActivity implements OnInitListener{

//public class RadioActivity extends ListActivity {
	
	private final static String TAG=RadioActivity.class.getSimpleName();
	
	private TextToSpeech mTts;
	//private TTS mTts;

	
	private NewsPersistence store;

	private final static int MY_DATA_CHECK_CODE = 1;
	
	private List<NewsItem> news;
	
	private NewsListItemAdapter adapter;

	public static final String VIEW_ONLY_KEY = "VIEW";
	
/*    private TTS.InitListener ttsInitListener = new TTS.InitListener() {
        public void onInit(int version) {
          turnOnRadio();
        }
      };*/

	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		

		
		try {
			store = new NewsPersistence();
			news = store.retrieveNewsItem();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e(TAG,"NewsPersistence init fail",e);
		}
		adapter = new NewsListItemAdapter(this);
		setListAdapter(adapter);
		//TODO: TTS initialization takes time to go up.
		// it's good for us to check whether the tts libary is installed or not firstly		
		// then we retrive the news from storage.
		// but the list adapter could be get the null news list
		
		Bundle bundle = this.getIntent().getExtras();
		if(!bundle.getBoolean(VIEW_ONLY_KEY))
		{
			Log.d(TAG, "radio broadcast is needed");
			checkTTSLib();
			AlertDialog.Builder builder = new AlertDialog.Builder(RadioActivity.this)
			.setTitle(R.string.radio_alert_dialog_label)
			.setMessage(R.string.radio_alert_message);
			builder.setPositiveButton(R.string.radio_alert_positive_button_cap, 
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							if(mTts != null)
							{	
								mTts.stop();
								mTts.shutdown();
							}
						}

					}).show();
		}
		else
		{
			Log.d(TAG, "radio is not needed");
		}
		
		
		

		
	}

	
	/* (non-Javadoc)
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		Log.d(TAG,"onListItemClick pos:" + position + " id:" + id);
		super.onListItemClick(l, v, position, id);
		
		NewsItem item = (NewsItem)getListView().getItemAtPosition(position);
		Bundle bundle = new Bundle();
		bundle.putString(NewsDetailActivity.SOURCE_BUNDLE_KEY, item.getNewsSource());
		bundle.putLong(NewsDetailActivity.DATE_BUNDLE_KEY, item.getPublishDate());
		bundle.putString(NewsDetailActivity.CLICKURL_BUNDLE_KEY, item.getClickUrl());
		bundle.putString(NewsDetailActivity.CONTENT_BUNDLE_KEY, item.getContent());
		
		Intent intent= new Intent(RadioActivity.this,NewsDetailActivity.class);
		intent.putExtras(bundle);
		startActivity(intent);
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	
	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG,"onDestroy");	
		if(mTts != null)
		{	
			mTts.stop();
			mTts.shutdown();
		}
		super.onDestroy();

	}


	private void checkTTSLib()
	{
		//for google android native tts
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);	
		
		//mTts = new TTS(this, ttsInitListener, true);

	}
	
	protected void onActivityResult(
	        int requestCode, int resultCode, Intent data) {
	    if (requestCode == MY_DATA_CHECK_CODE) {
	        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
	            // success, create the TTS instance
	            mTts = new TextToSpeech(this, (OnInitListener) this);
	            mTts.setLanguage(Locale.US);
	            //turnOnRadio();
	        } else {
	            // missing data, install it
	            Intent installIntent = new Intent();
	            installIntent.setAction(
	                TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
	            startActivity(installIntent);
	        }
	    }
	}
	
	private void turnOnRadio()
	{
		try {
			
			for(NewsItem item : news)
			{
				mTts.speak(item.getContent(), TextToSpeech.QUEUE_ADD, null);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e(TAG, "get stored news fail",e);
		}
		
	}


	//for google android native tts libarary
	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub
		Log.d(TAG, "TextToSpeech init done");
		turnOnRadio();
	}
	
	private class NewsListItemAdapter extends BaseAdapter{
		
		private LayoutInflater mInflater;
		
		private final SimpleDateFormat DATE_FORMAT=new SimpleDateFormat("yyyy-MM-dd");
		private final SimpleDateFormat TIME_FORMAT=new SimpleDateFormat("HH:mm");
		
		private Calendar cal = Calendar.getInstance();
		
		public NewsListItemAdapter(RadioActivity parent)
		{
			mInflater = LayoutInflater.from(parent);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return news.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return news.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;

			if(convertView == null)
			{
				Log.d(TAG, "convertView is null");
				convertView = mInflater.inflate(R.layout.news_list_item, null);
				holder = new ViewHolder();
				holder.source = (TextView)convertView.findViewById(R.id.news_list_item_source);
				holder.date = (TextView)convertView.findViewById(R.id.news_list_item_date);
				holder.title = (TextView)convertView.findViewById(R.id.news_list_item_title);
				convertView.setTag(holder);
			}
			else
			{
				Log.d(TAG, "convertView is not null");
				holder = (ViewHolder) convertView.getTag();
			}
			Log.d(TAG, "news.get(position): " +news.get(position).getNewsSource());
			holder.source.setText(news.get(position).getNewsSource());
			
			long unixTimeinMillis = news.get(position).getPublishDate()*1000;
			cal.setTimeInMillis(unixTimeinMillis);
			String pubDate = "";
			if(cal.before(new Date()))
			{
				pubDate = DATE_FORMAT.format(new Date(unixTimeinMillis));
			}
			{
				pubDate = TIME_FORMAT.format(new Date(unixTimeinMillis));
			}
			holder.date.setText(pubDate);
			
			holder.title.setText(news.get(position).getTitle());
			
			return convertView;
		}
		
        class ViewHolder {
            TextView source;
            TextView date;
            TextView title;
        }

		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0,0,0,R.string.radio_activity_option_menu_delete_all);
		menu.add(0,1,0,R.string.radio_activity_option_menu_read_all);
		menu.add(0,2,0,R.string.radio_activity_option_menu_stop_read);
		return super.onCreateOptionsMenu(menu);
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
		switch(item.getItemId())
		{
		    case 0:			
		    	store.removeAllNewsItems();	
		    	news.clear();
		    	adapter.notifyDataSetChanged();
		    	break;
		    case 1:
		    	checkTTSLib();
		    case 2:
		    	if(mTts != null)
		    	{
		    		mTts.stop();
		    		mTts.shutdown();
		    	}
			default:
				break;
		}
		return true;
	}

	
}
